<?php

namespace app\shop\controller\product;

use app\shop\controller\Controller;
use app\shop\model\product\ProductMark as MarkModel;

/**
 * 标记管理控制器
 */
class ProductMark extends Controller
{
    /**
     * 获取列表
     */
    public function index()
    {
        // 列表
        $list = MarkModel::listData($this->request->param(), $this->getData());
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 添加
     */
    public function add()
    {
        $model = new MarkModel;
        // 新增记录
        if ($model->add($this->postData())) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 编辑
     */
    public function edit($id)
    {
        // 详情
        $model = MarkModel::detail($id);
        // 更新记录
        if ($model->edit($this->postData())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除
     */
    public function delete($id)
    {
        $model = MarkModel::detail($id);
        if (!$model->remove()) {
            return $this->renderError('该标记使用中，删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

    /**
     *
     * audit
     * \think\response\Json
     * @return \think\response\Json
     * @Author kevin
     * @date 2024/5/23 11:57
     */
    public function audit()
    {
        $param  = $this->postData();
        $model  = new MarkModel;

        if (!isset($param['id'])) {
            return $this->renderError('id不能为空');
        }
        $param['id'] = is_array($param['id']) ? $param['id'] : [$param['id']];
        $detail      = $model->whereIn('id', $param['id'])->select();
        if ($detail->isEmpty()) {
            return $this->renderError('数据不存在');
        }
        $data = ['audit_status' => $param['audit_status'], 'remark' => $param['remark'] ?? ''];
        $num = 0;
        foreach ($detail as $item) {
            $res = $item->allowField(['audit_status', 'remark'])->save($data);
            if ($res) {
                $num++;
            }
        }
        return $this->renderSuccess($num > 0 ? "审核成功{$num}条" : '审核失败');
    }
}